package gl.java.network.transport.kcp.udp;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

@Slf4j
public class UmspUdpClient {
    public static final int MessageReceived = 0x99;
    private static int scanPort = 2555;

    public UmspUdpClient(int scanPort) {
        this.scanPort = scanPort;
    }


    private static class CLientHandler extends SimpleChannelInboundHandler<DatagramPacket> {

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
            log.info("recv udp:"+packet.content().getByte(1));
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) throws Exception {
            log.error("", e);
            ctx.close();
        }
    }

    static int i = 1;
    public static void main(String[] args) {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioDatagramChannel.class)
                    .handler(new CLientHandler());
            // udp.connect 或如果对端不可达,会收到ICMP包,本端会抛出异常
            final Channel ch = b.bind(0).sync().channel();
            b.connect("127.0.0.1", scanPort);

            ch.eventLoop().scheduleWithFixedDelay(new Runnable() {
                @Override
                public void run() {

                    ByteBuf heapBuffer = Unpooled.buffer(1024);
                    heapBuffer.writeByte((byte)i++);

//                    Unpooled.copiedBuffer("index:"+(i++), CharsetUtil.UTF_8)
                    ch.writeAndFlush(new DatagramPacket(heapBuffer,
                            new InetSocketAddress("127.0.0.1", scanPort)));
//                    log.info("send udp");
                }
            }, 3000, 1, TimeUnit.MILLISECONDS);


            ch.closeFuture().await();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }
}
